package cn.ibizlab.util.adapter.service.impl;

import net.ibizsys.central.cloud.core.service.SysServiceAPIRuntime;
import net.ibizsys.central.util.IEntityDTO;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

import static cn.ibizlab.util.adapter.util.constant.DELogicConstant.PARAM_DATAENTITY;

public class DefaultAdapterSysServiceAPIRuntime extends SysServiceAPIRuntime {

    @Override
    public Object invokeDEMethod(String strScope, String strDataEntityName, String strMethodName, Object objBody, String strKey, Object objTag) throws Throwable {
        return handlerResult(super.invokeDEMethod(strScope, strDataEntityName, strMethodName, objBody, strKey, objTag));
    }

    @Override
    public Object invokeDEMethod(String strScope, String strParentDEName, String strParentKey, String strDataEntityName, String strMethodName, Object objBody, String strKey, Object objTag) throws Throwable {
        return handlerResult(super.invokeDEMethod(strScope, strParentDEName, strParentKey, strDataEntityName, strMethodName, objBody, strKey, objTag));
    }

    /**
     * 返回参数处理: 剔除执行行为过程中设置的临时参数
     * @param obj
     * @return
     */
    protected Object handlerResult(Object obj){
        if(obj == null)
            return obj;

        if(obj instanceof IEntityDTO && !ObjectUtils.isEmpty(((IEntityDTO) obj).any())){

            IEntityDTO entityDTO = (IEntityDTO) obj;
            if(entityDTO.any().containsKey(PARAM_DATAENTITY))
                entityDTO.any().remove(PARAM_DATAENTITY);

            for(Map.Entry<String,Object> entry : entityDTO.any().entrySet()){
                Object fieldValue = entry.getValue();
                if(fieldValue != null && (fieldValue instanceof IEntityDTO || fieldValue instanceof Page || fieldValue instanceof List)){
                    entry.setValue(handlerResult(fieldValue));
                }
            }
        }
        else if(obj instanceof Page && !ObjectUtils.isEmpty(((Page<?>) obj).getContent())){
            ((Page<?>) obj).getContent().forEach(e-> handlerResult(e));
        }
        else if(obj instanceof List && !ObjectUtils.isEmpty(obj)){
            ((List<?>) obj).forEach(e-> handlerResult(e));
        }
        return obj;
    }

}
